package cn.sunlight.mm.service.impl;

import cn.sunlight.framework.annotation.HmComponent;
import cn.sunlight.mm.base.BaseService;
import cn.sunlight.mm.common.QuestionConst;
import cn.sunlight.mm.dao.*;
import cn.sunlight.mm.database.MmDaoException;
import cn.sunlight.mm.entity.PageResult;
import cn.sunlight.mm.entity.QueryPageBean;
import cn.sunlight.mm.pojo.*;
import cn.sunlight.mm.service.QuestionService;
import cn.sunlight.mm.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sunlight
 * @description: questionService
 * @date 2021/5/20
 * @Version v1.0
 */
@Slf4j
@HmComponent("questionService")
public class QuestionServiceImpl extends BaseService implements QuestionService {

    @Override
    public PageResult findListByPage(QueryPageBean queryPageBean) {
        log.debug("QuestionServiceImpl-queryPageBean:{}",queryPageBean);
        if (queryPageBean.getQueryParams()==null){
            Map map=new HashMap();
            //查询基础题库
            map.put("isClassic",0);
            queryPageBean.setQueryParams(map);
        }

        try {
            SqlSession session = getSession();
            QuestionDao questionDao = getDao(session, QuestionDao.class);
            //获取结果集
            List<Question> questionList=questionDao.selectListByPage(queryPageBean);
            //获取记录数
            Long total=questionDao.selectCount(queryPageBean);
            session.close();
            return new PageResult(total,questionList);
        }catch (MmDaoException e){
            e.printStackTrace();
            log.error(e.getMessage());
            throw  new MmDaoException(e.getMessage());
        }
    }

    @Override
    public void addOrUpdate(Question question) {
        SqlSession session = getSession();
        try {
            log.debug("Service addOrUpdate:{}",question);

            //保存题目信息
            updateQuestion(session,question);

            //保存题目选项信息
            updateQuestionItem(session,question);

            //保存标签信息（题目与标签关系）
            updateQuestionTag(session,question);

            //更新企业及行业信息
            updateCompany(session,question);

            //保存提交
            commitAndCloseSession(session);
        }catch (MmDaoException e){
            //回滚
            rollbackAndCloseSession(session);
            e.printStackTrace();
            log.error(e.getMessage());
            throw new MmDaoException(e.getMessage());
        }
    }

    @Override
    public PageResult findClassicByPage(QueryPageBean pageBean) {
        log.info("QuestionService findClassicByPage:{}",pageBean);
        SqlSession session = getSession();
        QuestionDao questionDao = getDao(session, QuestionDao.class);
        if (pageBean.getQueryParams()==null){
            pageBean.setQueryParams(new HashMap());
        }
        //查询精选题目
        pageBean.getQueryParams().put("isClassic",1);
        List<Question> questionList = questionDao.selectIsClassicByPage(pageBean);
        // 获取每条记录的审核状态
        for (Question question:questionList){
            ReviewLogDao reviewLogDao = getDao(session, ReviewLogDao.class);
            ReviewLog reviewLog = reviewLogDao.selectLastByQuestionId(question.getId());
            if (reviewLog==null){
                reviewLog = new ReviewLog();
                reviewLog.setStatus(0);
                reviewLog.setComments("");
                reviewLog.setReviewer("");
                reviewLog.setCreateDate("");
            }
            question.setReviewLog(reviewLog);
        }
        //获取总记录数
        Long totalCount = questionDao.selectCountIsClassicByPage(pageBean);
        closeSession(session);
        return new PageResult(totalCount,questionList);
    }

    /**
     * 更新公司及行业信息
     * @param session
     * @param question
     */
    private void updateCompany(SqlSession session, Question question) {
        // 更新公司信息
        CompanyDao companyDao = getDao(session, CompanyDao.class);
        Company company = question.getCompany();
        company.setUserId(question.getUserId());
        companyDao.updateCompanyCity(company);
        // 更新公司及行业关系
        // 删除旧公司行业关系
        companyDao.deleteCompanyIndustryByCompanyId(company.getId());
        // 新增企业及行业关系
        for (Industry industry:company.getIndustryList()){
            //构建关系
            Map map=new HashMap();
            map.put("companyId",company.getId());
            map.put("industryId",industry.getId());
            companyDao.addCompanyIndustry(map);
        }
    }

    /**
     * 更新题目标签关系
     * @param session
     * @param question
     */
    private void updateQuestionTag(SqlSession session, Question question) {
        TagDao tagDao = getDao(session, TagDao.class);
        //删除旧的关系
        tagDao.deleteTagListByQuestionId(question.getId());
        //新增关系
        //遍历标签
        for (Tag tag:question.getTagList()){
            //构建关系（questionId，tagId）
            Map map = new HashMap<>();
            map.put("questionId",question.getId());
            map.put("tagId",tag.getId());
            tagDao.addQuestionTag(map);
        }
    }

    /**
     * 更新题目选项
     * @param session
     * @param question
     */
    private void updateQuestionItem(SqlSession session, Question question) {
        // 构建QuestionItemDao对象
        QuestionItemDao questionItemDao = getDao(session, QuestionItemDao.class);
        // 遍历选项列表，逐一保存
        for (QuestionItem questionItem:question.getQuestionItemList()){
            // 其中某一题目选项
            // 设置选项的QuestionId
            questionItem.setQuestionId(question.getId());
            if (questionItem.getContent()==null||questionItem.getContent().length()==0){
                if (questionItem.getImgUrl()==null||questionItem.getImgUrl().length()==0){
                    continue;
                }
            }

            // 判断是添加还是更新
            if (questionItem.getId()==0){
                // 保存
                questionItemDao.addQuestionItem(questionItem);
            }else{
                //更新
                questionItemDao.updateQuestionItem(questionItem);
            }
        }
    }

    /**
     * 更新题目基本信息
     * @param session
     * @param question
     */
    private void updateQuestion(SqlSession session, Question question) {
        //对题目做初始化（isClassic=0，status=0，reviewStatus=0，createDate）
        question.setIsClassic(QuestionConst.ClassicStatus.CLASSIC_STATUS_NO.ordinal());
        question.setStatus(QuestionConst.Status.PRE_PUBLISH.ordinal());
        question.setReviewStatus(QuestionConst.ReviewStatus.PRE_REVIEW.ordinal());
        question.setCreateDate(DateUtils.parseDate2String(new Date()));
        QuestionDao questionDao = getDao(session, QuestionDao.class);
        if (question.getId()==0){
            //新增
            questionDao.add(question);
            log.debug("新增成功: question:id:{}",question.getId());
        }else{
            //更新
            questionDao.update(question);
            log.debug("更新成功");
        }
    }

}
